package com.cdl.library.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.cdl.library.R;
import com.cdl.library.eneity.MoreItem;
import com.cdl.library.listener.MoreButtonListener;
import com.cdl.library.listener.MoreButtonLongListener;

import java.util.ArrayList;
import java.util.List;

/***
 * 手机端topBar统一类型
 * 注意：不能在外部设置这个控件的高度
 * @author Administrator
 */
public class MoreButton extends RelativeLayout {

    private final TextView tv_content;
    private ImageView iv_right;
    private View view_top;
    private TextView tv_right_content;

    public MoreButton(Context context) {
        this(context, null);
    }

    public MoreButton(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    View view;
    String title_content = "";
    boolean showright;
    View mybutton_click;
    View view_bottom;
    boolean showbottom;
    boolean showtop;
    boolean isShowDateSources;
    boolean isClickHideDataList = true;
    List<MoreItem> dateSources = new ArrayList<>();
    private String right_content;
    RecyclerView rcMoreBtn;
    int currentPosition = 0;
    private OnExpandDataListener onExpandDataListener;

    public MoreButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.More_Button);
        title_content = a.getString(R.styleable.More_Button_title_content);
//        defaultTextColor = a.getInt(R.styleable.More_Button_text_font_color, 0xffFFFFFF);
        showright = a.getBoolean(R.styleable.More_Button_showright, true);
        showbottom = a.getBoolean(R.styleable.More_Button_showbottom, true);
        showtop = a.getBoolean(R.styleable.More_Button_showtop, false);
        isShowDateSources = a.getBoolean(R.styleable.More_Button_showDateSources, false);
        right_content = a.getString(R.styleable.More_Button_right_content);
        float textSize = a.getDimensionPixelSize(R.styleable.More_Button_text_size, 0);
        view = LayoutInflater.from(context).inflate(R.layout.more_button, null);
        rcMoreBtn = view.findViewById(R.id.rcMoreBtn);
        rcMoreBtn.setLayoutManager(new LinearLayoutManager(context));
        tv_right_content = (TextView) view.findViewById(R.id.tv_right);
        tv_right_content.setText(right_content);

        tv_content = (TextView) view.findViewById(R.id.tv_content);
        tv_content.setText(title_content);

        view_top = view.findViewById(R.id.view_top);
        view_bottom = view.findViewById(R.id.view_bottom);

        if (textSize > 0) {
            tv_content.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
        }


        view_top.setVisibility(showtop ? View.VISIBLE : View.INVISIBLE);
        view_bottom.setVisibility(showbottom ? View.VISIBLE : View.INVISIBLE);

        iv_right = (ImageView) view.findViewById(R.id.iv_right);
        iv_right.setVisibility(showright ? View.VISIBLE : View.INVISIBLE);

        mybutton_click = view.findViewById(R.id.mybutton_click);
        mybutton_click.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isShowDateSources && dateSources.size() > 0) {
                    if (rcMoreBtn.getVisibility() == View.VISIBLE) {
                        rcMoreBtn.setVisibility(View.GONE);
                        iv_right.setBackgroundResource(R.drawable.vector_arrow_right);
                    } else {
                        rcMoreBtn.setVisibility(View.VISIBLE);
                        iv_right.setBackgroundResource(R.drawable.vector_arrow_down);
                        setRcDates();
                        if (onExpandDataListener != null) {
                            rcMoreBtn.post(onExpandDataListener::onExpand);
                        }
                    }
                }
                if (listener != null) {
                    listener.clickView(MoreButton.this);
                }
            }
        });

        //长按事件
        mybutton_click.setOnLongClickListener(new OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                Log.i("cdl", "===holder.itemView==触发长按");
                if (longListener != null) {
                    longListener.clickLongView(MoreButton.this);
                }
                return true;
            }
        });

        mybutton_click.setOnKeyListener(new OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (onKeyListener != null) {
                    return onKeyListener.onKey(MoreButton.this, keyCode, event);
                }
                return false;
            }
        });

        if (right_content != null && !right_content.isEmpty()) {
            tv_right_content.setVisibility(View.VISIBLE);
            tv_right_content.setText(right_content);
        }
        //缩进
        if (isShowDateSources) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) rcMoreBtn.getLayoutParams();
            layoutParams.leftMargin = getResources().getDimensionPixelOffset(R.dimen.view_child_more_left_margin1);
            rcMoreBtn.setLayoutParams(layoutParams);
        }
        addView(view);
        a.recycle();
    }


    private class BaseViewHolder extends RecyclerView.ViewHolder {
        TextView showTextView;
        View view_top;
        View view_bottom;
        ImageView cBox;

        public BaseViewHolder(@NonNull View itemView) {
            super(itemView);
            showTextView = itemView.findViewById(R.id.tv_content);
            view_top = itemView.findViewById(R.id.view_top);
            view_bottom = itemView.findViewById(R.id.view_bottom);
            cBox = itemView.findViewById(R.id.cBox);
            view_top.setVisibility(View.GONE);
            view_bottom.setVisibility(View.GONE);
        }

    }

    private void setRcDates() {
        RecyclerView.Adapter<BaseViewHolder> adapter = new RecyclerView.Adapter<BaseViewHolder>() {
            @NonNull
            @Override
            public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(getContext()).inflate(R.layout.more_button_checkcircle, parent, false);
                BaseViewHolder viewHolder = new BaseViewHolder(view);
                return viewHolder;
            }

            @Override
            public void onBindViewHolder(@NonNull BaseViewHolder holder, @SuppressLint("RecyclerView") int position) {
                holder.view_bottom.setVisibility(VISIBLE);
                holder.showTextView.setText(dateSources.get(position).name);
                holder.cBox.setImageResource(currentPosition == holder.getAdapterPosition() ? R.drawable.radio_button_checked : R.drawable.radio_button_unchecked);
                holder.itemView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        currentPosition = holder.getAdapterPosition();
                        Log.i("cdl", "=====选中=" + currentPosition);
                        notifyDataSetChanged();
                        MoreItem moreItem = dateSources.get(position);
                        if (isClickHideDataList) {
                            rcMoreBtn.setVisibility(View.GONE);
                            iv_right.setBackgroundResource(R.drawable.vector_arrow_right);
                        } else {
                            rcMoreBtn.setVisibility(View.VISIBLE);
                            iv_right.setBackgroundResource(R.drawable.vector_arrow_down);
                        }
                        if (mIDatesClickResult != null) {
                            mIDatesClickResult.datesClickResult(moreItem, position);
                        }
                        if (isShowDateSources) {
                            setContentText(moreItem.name);
                        }
                    }
                });
            }

            @Override
            public int getItemCount() {
                return dateSources.size();
            }
        };
        rcMoreBtn.setAdapter(adapter);
    }

    public void checkPosition(int index) {
        this.currentPosition = index;
        if (isShowDateSources && dateSources != null && currentPosition < dateSources.size()) {
            setContentText(dateSources.get(currentPosition).name);
        }
        RecyclerView.Adapter adapter = rcMoreBtn.getAdapter();
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
    }

    public int getCheckPosition() {
        return currentPosition;
    }

    public void setClickHideDataList(boolean clickHideDataList) {
        isClickHideDataList = clickHideDataList;
    }

    /**
     * 设置它，就无需设置setOnMoretListener
     * 这个接口可以自动完成大多数操作，回调被选中的项
     * setOnMoretListener的作用在于：点击moreButton按钮，UI可能会有其它变化，特意留下来而已
     * =====>注意<======：外部引用om.ys.model.view.MoreButton，千万不能设置固定高度
     **/
    public void setShowDateSources(int currentPosition, List<MoreItem> data, IDatesClickResult mIDatesClickResult) {
        this.dateSources = data;
        this.currentPosition = currentPosition;
        this.mIDatesClickResult = mIDatesClickResult;
        if (isShowDateSources && data != null && currentPosition < data.size()) {
            setContentText(data.get(currentPosition).name);
        }
    }

    public void setContentText(String content) {
        Log.e("cdl", "currentCodeShow=000=" + content);
        tv_right_content.setVisibility(VISIBLE);
        tv_right_content.setText(content);
    }

    public void setRightImg(boolean isShow) {
        if (isShow) {
            iv_right.setVisibility(VISIBLE);
        } else {
            iv_right.setVisibility(GONE);
        }
    }

    public TextView getTvContent() {
        return tv_content;
    }

    public void setTextTitle(String text) {
        tv_content.setText(text);
    }

    public String getTitleContent() {
        return tv_content.getText().toString();
    }

    public void setRightImage(int imageId) {
        iv_right.setBackgroundResource(imageId);
    }

    public void setRightText(String text) {
        tv_right_content.setText(text);
    }

    public String getRightContent() {
        return tv_right_content.getText().toString();
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            layout(l, t, r, b);
        }
    }

    /**
     * 通用情况下不建议设置这个接口，大多数操作都可以setShowDateSources自动完成，回调选中的选项
     * 它的作用在于：点击更多，UI可能会有其它变化，特意把它留下来而已
     **/
    MoreButtonListener listener;

    public void setOnMoretListener(MoreButtonListener listener) {
        this.listener = listener;
    }

    MoreButtonLongListener longListener;

    public void setOnMoreLongListener(MoreButtonLongListener listener) {
        this.longListener = listener;
    }

    public void setOnExpandDataListener(OnExpandDataListener listener) {
        this.onExpandDataListener = listener;
    }

    private OnKeyListener onKeyListener;

    public void setKeyListener(OnKeyListener onKeyListener) {
        this.onKeyListener = onKeyListener;
    }

    public boolean rcMoreBtnIsVisible() {
        return rcMoreBtn.getVisibility() == View.VISIBLE;
    }

    IDatesClickResult mIDatesClickResult;

    public interface IDatesClickResult {
        void datesClickResult(MoreItem result, int position);
    }

    public interface OnExpandDataListener {
        void onExpand();
    }
}
